import { IBusiness } from "./IBusiness";

/*
@name: BusinessCenter
@desc: 事务中心,管理事务
@author: timoo
@date: 2022/09/26
*/
export class BusinessCenter {
    private _businessMap:Map<{new ():IBusiness}, IBusiness> = new Map<{new ():IBusiness}, IBusiness>();
    private static created:boolean = false;
    constructor(){
        if(BusinessCenter.created){
            throw new Error("BusinessCenter 是单例");
        }
        BusinessCenter.created = true;
    }
    /**
     * 同时初始化多个事务，多用在APP\Game启动时
     * @param businessClassList 
     */
    init(businessClassList:{new ():IBusiness}[]):void{
        for (let i = 0; i < businessClassList.length; i++) {
            const BClass = businessClassList[i];
            this.start(BClass);
        }
    }

    start(businessClass:{new ():IBusiness}, ...args):IBusiness{
        console.assert(businessClass != undefined, "businessClass is null");
        let business:IBusiness = this._businessMap.get(businessClass)
        if(!business){
            business = new businessClass();
            this._businessMap.set(businessClass, business);
        }
        return business.start.apply(business, args);
    }

    get(businessClass:{new ():IBusiness}):IBusiness{
        return this._businessMap.get(businessClass);
    }

    stop(businessClass:{new ():IBusiness}):void{
        console.assert(!businessClass != undefined, "businessClass is null");
        if(this.get(businessClass)){
            this.get(businessClass).stop();
        }
    }

    pause(businessClass:{new ():IBusiness}):void{
        console.assert(!businessClass != undefined, "businessClass is null");
        if(this.get(businessClass)){
            this.get(businessClass).pause();
        }
    }

    release(businessClass:{new ():IBusiness}):boolean{
        console.assert(!businessClass != undefined, "businessClass is null");
        if(this.get(businessClass)){
            this.get(businessClass).release();
            return this._businessMap.delete(businessClass);
        }
        return false;
    }

    destroy():void{
        this._businessMap.forEach((value:IBusiness, key:{new ():IBusiness})=>{
            value.stop();
        })
        this._businessMap.clear();
    }
}

/**
 * 事务中心，用于增加常驻逻辑，例如基础网络链接的心跳，业务逻辑中服务器的消息推送等
 */
export var businessCenter:BusinessCenter = new BusinessCenter();